package cn.weiwh.mailsend.mail.manager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
//@Component
public class MailManagerSend {
    private static final Logger logger= LoggerFactory.getLogger(MailManagerSend.class);
    public static void sendMail(String title,String msg){
        // 收件人电子邮箱
        //String to = "chenjiehan@gd.chinamobile.com";
        //String to[] = { "chenjiehan@gd.chinamobile.com" };// 发送到那里
        String to[] = { "2207242978@qq.com","1162868738@qq.com" };
        // 发件人电子邮箱
        String from = "gywgfxs4@gd.chinamobile.com";
        //发件人用户名
        String user="gywgfxs4@gd.chinamobile.com";
        //发件人账户密码
        String password="Gmcc@1234";
        // 指定发送邮件的主机为 localhost
        String host = "smtp.gd.chinamobile.com";

        // 获取系统属性
        Properties properties = System.getProperties();

        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.smtp.port", "25");
        properties.setProperty("mail.smtp.auth", "true");
        properties.setProperty("mail.user", user);
        properties.setProperty("mail.password", password);
        properties.setProperty("mail.smtp.timeout","5000");

        Authenticator auth = new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("gywgfxs4@gd.chinamobile.com", "Gmcc@1234");
            }
        };
        // 获取默认的 Session 对象。
        Session session = Session.getDefaultInstance(properties,auth);

        try{
            // 创建默认的 MimeMessage 对象。
            MimeMessage message = new MimeMessage(session);

            // Set From: 头部头字段
            message.setFrom(new InternetAddress(from));

            // Set To: 头部头字段
            InternetAddress[] sendTo = new InternetAddress[to.length];
            for (int i = 0; i < to.length; i++) {
                logger.info("wwh--发送到:" + to[i]);
                sendTo[i] = new InternetAddress(to[i]);
            }
            message.addRecipients(Message.RecipientType.TO, sendTo);
            // Set Subject: 头字段
            message.setSubject(title,"utf-8");

            // 发送 HTML 消息, 可以插入html标签
            message.setContent(msg, "text/html;charset=utf-8" );
            logger.info("wwh--准备发送的内容："+msg);
            // 发送消息
            Transport.send(message);

            logger.info("wwh:发送完毕！");
            logger.info("wwh:send email success！");
        }catch (MessagingException mex) {
            logger.info("wwh:发送失败！");
            logger.info("wwh:send email error！---"+mex.getMessage());
            mex.printStackTrace();
        }
    }
}
